package com.as.struts.action;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.as.service.IUsuarioService;
import com.as.service.factory.IServiceFactory;
import com.as.service.user.UserContainer;
import com.as.service.user.UserView;
import com.as.service.util.IConstants;
import com.as.struts.form.Form;

public class LoginAction extends BaseAction {
	
	public ActionForward login(ActionMapping am, ActionForm af, HttpServletRequest req, HttpServletResponse res) { 
		Form f = (Form)af;
		
		if(!isValid(f, am, req)) {
			return am.getInputForward();
		}
		
		IServiceFactory factory = (IServiceFactory) servlet.getServletContext().getAttribute(IConstants.SERVICE_FACTORY_INTERFACE_KEY);
		IUsuarioService usuarioService = factory.createServiceAuthentication();
		
		UserView user = usuarioService.login(f.getString("password"),f.getString("user"));
		if (user == null) {
			setError("invalid.authentication", req);
			return am.getInputForward();
		}
		
		HttpSession session = req.getSession(true);
		
		UserContainer userContainer = new UserContainer();
		userContainer.setUserView(user);
		session.setAttribute(IConstants.USER_CONTAINER_KEY, userContainer);
		
		if (!user.isEnabled()) {
			setError("user.disabled", req);
			return am.getInputForward();
		} else {
			return am.findForward("success");
		}
	}

	public ActionForward logout(ActionMapping am, ActionForm af, HttpServletRequest req, HttpServletResponse res) {
		req.getSession().invalidate();
		return null;
	}
}